/*
 * Copyright 2016 czy1121
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.richard.library.basic.dialog;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Build;
import android.provider.Settings;
import android.view.View;

import androidx.core.content.FileProvider;

import com.richard.library.basic.R;
import com.richard.library.basic.util.ActivityManager;
import com.richard.library.basic.util.ToastUtil;

import java.io.File;

/**
 * <pre>
 * Description : APP版本更新工具类
 * Author : admin-richard
 * Date : 2017/11/28 14:15
 * Changelog:
 * Version            Date            Author              Detail
 * ----------------------------------------------------------------------
 * 1.0         2017/11/28 14:15      admin-richard         new file.
 * </pre>
 */
public final class UpdateUtil {
    private static final String PREFS = "ezy.update.prefs";
    private static final String KEY_UPDATE = "ezy.update.prefs.update";

    public static void clean(Context context) {
        try {
            SharedPreferences sp = context.getSharedPreferences(PREFS, 0);
            File file = new File(context.getExternalCacheDir(), sp.getString(KEY_UPDATE, "") + ".apk");
            if (file.exists()) {
                file.delete();
            }
            sp.edit().clear().apply();
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
    }

    /**
     * 安装APK安装包
     */
    @SuppressLint("QueryPermissionsNeeded")
    public static void install(Activity activity, File apkFile, boolean force) {
        if (apkFile == null) {
            ToastUtil.showLong("请提供APK安装包");
            return;
        }

        if(!apkFile.exists()){
            ToastUtil.showLong("安装文件文件不存在");
            return;
        }

        if(!apkFile.isFile()){
            ToastUtil.showLong("安装包不是APK文件");
            return;
        }

        try {
            if (!checkNonMarketAppsPermStatus(activity)) {
                new PromptDialog.Builder(activity)
                        .setTitle(R.string.dialog_title)
                        .setMessage("您还未开启允许安装来自未知来源应用权限，请在系统设置中开启")
                        .setLeftBtn(R.string.dialog_cancel_label, null)
                        .setRightBtn("去开启", new PromptDialog.OnDialogClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, View view) {
                                startInstallPermissionSettingActivity(activity);
                                dialogInterface.dismiss();
                            }
                        })
                        .create()
                        .show();
                return;
            }

            String mimeDefault = "application/vnd.android.package-archive";
            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
                intent.setDataAndType(Uri.fromFile(apkFile), mimeDefault);
            } else {
                Uri uri = FileProvider.getUriForFile(activity, activity.getApplication().getPackageName() + ".provider", apkFile);
                intent.setDataAndType(uri, mimeDefault);
                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION);
            }
            activity.startActivity(intent);

            //如果APK安装界面存在，携带请求码跳转。使用forResult是为了处理用户 取消 安装的事件。外面这层判断理论上来说可以不要，但是由于国内的定制，这个加上还是比较保险的
            if (activity.getPackageManager().queryIntentActivities(intent, 0).size() > 0) {
                activity.startActivityForResult(intent, 2);
            }

            SharedPreferences sp = activity.getSharedPreferences(PREFS, 0);
            sp.edit().putString(KEY_UPDATE, apkFile.getName()).apply();
            if (force) {
                ActivityManager.get().exitApp(true);
            }
        } catch (Throwable e) {
            e.printStackTrace();
            ToastUtil.showLong("安装时出现错误");
        }
    }

    /**
     * 开启设置安装未知来源应用权限界面
     */
    public static void startInstallPermissionSettingActivity(Activity activity) {
        if (activity == null) {
            return;
        }
        Intent intent = new Intent();
        if (Build.VERSION.SDK_INT >= 26) {
            intent.setAction(android.provider.Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES);
        } else {
            intent.setAction(android.provider.Settings.ACTION_SECURITY_SETTINGS);
        }
        activity.startActivityForResult(intent, 1);
    }


    /**
     * 检查系统是否开启可安装未知来源应用
     */
    public static boolean checkNonMarketAppsPermStatus(Context context) {
        boolean hasInstallPermission = false;

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            hasInstallPermission = context.getPackageManager().canRequestPackageInstalls();
        } else if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1) {
            hasInstallPermission = Settings.Secure.getInt(
                    context.getContentResolver()
                    , Settings.Secure.INSTALL_NON_MARKET_APPS, 0
            ) == 1;
        } else {
            hasInstallPermission = Settings.Global.getInt(
                    context.getContentResolver()
                    , Settings.Global.INSTALL_NON_MARKET_APPS, 0
            ) == 1;
        }

        return hasInstallPermission;
    }

//    @Override
//    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//        super.onActivityResult(requestCode, resultCode, data);
//        if (resultCode == RESULT_OK) {
//            if (requestCode == 1) {
//                openAPKFile();
//            }
//        } else {
//            if (requestCode == 1) {
//                //下午4:31 8.0手机位置来源安装权限
//                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
//                    boolean hasInstallPermission = getPackageManager().canRequestPackageInstalls();
//                    if (!hasInstallPermission) {
//                        LogUtils.e(TAG, "没有赋予 未知来源安装权限");
//                        showUnKnowResourceDialog();
//                    }
//                }
//            } else if (requestCode == 2) {
//                // CnPeng 2018/8/2 下午4:31 在安装页面中退出安装了
//                LogUtils.e(TAG, "从安装页面回到欢迎页面--拒绝安装");
//
//                showApkInstallDialog();
//            }
//        }
//    }
}